package com.lixin.web.webSocket.impl;

import cn.hutool.core.bean.BeanUtil;
import com.lixin.constants.ExceptionConstants;
import com.lixin.entity.Friendships;
import com.lixin.entity.Users;
import com.lixin.exception.DuplicateFriendRequestException;
import com.lixin.exception.RequestException;
import com.lixin.model.enums.NotifyEnum;
import com.lixin.model.notify.AddFriendNotify;
import com.lixin.model.notify.NotifyRes;
import com.lixin.model.request.AcceptFriendRequest;
import com.lixin.model.response.FindAllFriendsResponse;
import com.lixin.model.response.Response;
import com.lixin.service.IFriendshipsService;
import com.lixin.web.netty.NettyServerStarter;
import com.lixin.web.netty.NettyUtil;
import com.lixin.web.netty.UserSessionManager;
import com.lixin.web.webSocket.FriendshipsManager;
import com.lixin.web.webSocket.NotificationManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lixin.service.IUsersService;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

/**
 * Description:
 * Copyright:   Copyright (c)2023
 * Company:     sci
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2023-08-02 22:18:04
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2023-08-02     张李鑫                     1.0         1.0 Version
 */
@Component("friends")
public class FriendshipsManagerImpl implements FriendshipsManager {

    @Autowired
    private IFriendshipsService friendshipsService;

    @Autowired
    private IUsersService usersService;
    @Autowired
    private NotificationManager notificationManager;

    /**
     * 添加好友
     *
     * @param addFriendNotify
     * @return
     */
    @Override
    public Response<Object> addFriend(AddFriendNotify addFriendNotify) {
        if (addFriendNotify == null || addFriendNotify.getRecipientId() == null) {
            return Response.error("recipientId is null");
        }
        Users user = usersService.findById(NettyUtil.getAttr(NettyServerStarter.ctxThreadLocal.get().channel(), NettyUtil.UID));
        addFriendNotify.setRequesterId(user.getUserId());
        addFriendNotify.setRequesterName(user.getUsername());
        friendshipsService.addFriend(addFriendNotify.getRecipientId(), NettyUtil.getAttr(NettyServerStarter.ctxThreadLocal.get().channel(), NettyUtil.UID));
        Integer recipientId = addFriendNotify.getRecipientId();
        //通知处理类去处理通知
        notificationManager.sendNotification(
                NotifyRes.createNotify(
                        NotifyEnum.FriendRequest.getValue(),
                        addFriendNotify),
                 recipientId);
        return Response.success();
    }

    /**
     * 查询当前登录人所有好友列表
     *
     * @return
     */
    @Override
    public Response<List<FindAllFriendsResponse>> findAllFriends() {
        return Response.success(
                BeanUtil.copyToList(
                        friendshipsService.findAllFriends(NettyUtil.getUserId()),
                        FindAllFriendsResponse.class)
        );
    }

    /**
     * 接受好友请求
     *
     * @param acceptFriendRequest
     * @return
     */
    @Override
    public Response<Object> acceptFriendRequest(AcceptFriendRequest acceptFriendRequest) {
        Friendships requestFriendship = friendshipsService.selectById(acceptFriendRequest.getFriendsId());
        Integer userId = NettyUtil.getAttr(NettyServerStarter.ctxThreadLocal.get().channel(), NettyUtil.UID);

        //数据权限检查
        if (requestFriendship == null || !requestFriendship.getFriendId().equals(userId)) {
            throw new RequestException(ExceptionConstants.PARAMS_ERROR);
        }
        //检查是否是好友
        if (friendshipsService.isFriend(requestFriendship.getUserId(), userId)) {
            throw new DuplicateFriendRequestException();
        }

        Date date = new Date();
        requestFriendship.setTimestamp(date);
        friendshipsService.addOrUpdate(requestFriendship);
        friendshipsService.addOrUpdate(friendshipsService.builder(date, userId, requestFriendship.getUserId()));
        return Response.success();
    }

    /**
     * 删除好友
     *
     * @param friendId
     * @return
     */
    @Override
    public Response<Object> deleteFriend(Integer friendId) {
        return friendshipsService.deleteFriend(friendId, NettyUtil.getUserId()) > 0 ? Response.success() : Response.error("删除失败");
    }


    /**
     * 根据用户名查询好友
     *
     * @param userName
     * @return
     */
    @Override
    public Response<Users> findFriendByUsername(String userName) {
        return Response.success(usersService.findFriendByUsername(userName));
    }
}
